const { Text2Image, setEnvVariable } = require("@baiducloud/qianfan");
const config = require("../config/base");
const axios = require('axios');

class ImageController {
  // 将 getAccessToken 改为实例方法
  static async generateImage(ctx) {
    try {
      setEnvVariable('QIANFAN_ACCESS_KEY', config.qianfan.apiKey);
      setEnvVariable('QIANFAN_SECRET_KEY', config.qianfan.secretKey);
      const client = new Text2Image();
      console.log('收到图像生成请求:', ctx.request.body);
      const { prompt } = ctx.request.body;

      // 调用文生图 API
      const imageResponse = await client.text2Image({
        prompt,
      });

      console.log('百度 API 响应:', imageResponse);

      // 检查错误响应
      if (!imageResponse || !imageResponse?.data || !imageResponse?.data?.[0]?.b64_image) {
        throw new Error('生成图像失败');
      }

      // 添加 base64 图片头
      const imageBase64 = `data:image/png;base64,${imageResponse?.data?.[0].b64_image}`;

      ctx.body = {
        success: true,
        data: imageBase64
      };
    } catch (error) {
      console.error('图像生成错误:', {
        message: error.message,
        response: error.response?.data || error.message
      });
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: error.message
      };
    }
  }
}

module.exports = ImageController;